const Router = require('koa-router')
const mongo = require('../../schedma/db')
const router = new Router()

router.get('/user/self', async (ctx) => {
  const data = await mongo.UserInfo.findOne({username: ctx.user.name}, {url: 1, _id: 0, nickname: 1, instroce: 1})
  if (data) {
    ctx.body = data
  } else {
    ctx.body = {
      code: 500,
      message: 'no message'
    }
  }
})

router.post('/user/self', async (ctx) => {
  const data = await mongo.UserInfo.updateOne({username: ctx.user.name}, {$set: ctx.request.body})
  if (data) {
    ctx.body = true
  } else {
    ctx.body = {
      code: 500,
      message: 'no message'
    }
  }
})

router.post('/users', async (ctx) => {
  const {username, ...params } = ctx.request.body
  const data = await mongo.UserInfo.updateOne({username: username}, {$set: params})
  if (data) {
    ctx.body = true
  } else {
    ctx.body = {
      code: 500,
      message: 'no message'
    }
  }
})

router.get('/users', async (ctx) => {
  const page = +ctx.request.query.curPage
  const pageSize = +ctx.request.query.pageSize
  const length = await mongo.UserInfo.count()
  const data = await mongo.UserInfo.find({}, {_id: 0, __v: 0}).skip((page - 1) * pageSize).limit(pageSize)
  if (data) {
    ctx.body = {
      items: data,
      page: {
        total: Math.ceil(length / pageSize),
        page,
        pageSize,
      }
    }
  } else {
    ctx.body = {
      code: 500,
      message: 'no message'
    }
  }
})

router.delete('/users', async ctx => {
  const name = ctx.request.query.username
  const data = await mongo.UserInfo.remove({username: name})
  if (data.n) {
    ctx.body = true
  } else {
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '找不到该用户'
    }
  }
})

router.post('/user/form', async (ctx) => {
  // const data = await mongo.ImageSchemal.find({username: ctx.user.name}, {url: 1, _id: 0})
  ctx.body = true
})

module.exports = router